package cn.jsp.dao;

import cn.jsp.domain.Produce;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Repository

public class ProduceDao {
    @Autowired
    DataSource dataSource;
    public List<Produce> query(String sql){
        List<Produce> produces=new ArrayList<>();
        try (
                Connection connection =dataSource.getConnection();
                PreparedStatement preparedStatement=connection.prepareStatement(sql);
                ResultSet resultSet=preparedStatement.executeQuery())
        {
            while(resultSet.next()){
                //将resultSet转化为实例对象，可以声明接口简化过程
                Produce produce=new Produce(resultSet.getString("name"),resultSet.getDouble("price"));
                produces.add(produce);
                System.out.println(resultSet.getString("name"));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return produces;
    }
}
